package com.jswlw.config;

import lombok.val;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @author 吴维斌 E-mail:wuweibin0817@163.com
 * @version 创建时间：${date} ${time}
 */
@Configuration
@ConditionalOnProperty("okhttp.enabled")
@EnableConfigurationProperties(OkhttpProperties.class)
public class OkhttpAutoConfiguration {

    @Autowired
    private OkhttpProperties properties;

    @Bean
    @ConditionalOnClass({OkHttpClient.class, DefaultHttpClient.class})
    @ConditionalOnMissingBean(DefaultHttpClient.class)
    public DefaultHttpClient httpClient() {
        val client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(properties.getRetryOnConnectionFailure())
                .connectTimeout(properties.getConnectTimeout(), TimeUnit.MILLISECONDS)
                .readTimeout(properties.getReadTimeout(), TimeUnit.MILLISECONDS)
                .writeTimeout(properties.getWriteTimeout(), TimeUnit.MILLISECONDS)
                .build();
        return DefaultHttpClient.of(client);
    }
}